package com.yq.ylmall.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {
    // 后台秘钥
    private static String adminkey ="asdojoj@!#!!#kashahsj^%&#$ahnajkdasj*@kahdk321232";
    //前台秘钥
    private static String userkey="dnash%^%$kahdoasj!!@lkahdoiasjo(*klshfk2321";
    //过期时间，单位为小时
    private static Integer expire = 24;
    // 签名是有谁生成
    private static  String issuser="yourlife";
    // 签名的主题
    private static  String subject="yourlife token";
    // 签名的观众
    private static  String client="yourlifeapp";
    //sha 2022-06-20  sdf242343243243242 ,1   ou234o290f98w4j2l3j4l32,ldsu932949797924o
    public void setAdminkey(String key){
        JwtUtils.adminkey =key;
    }
    public void setUserkey(String key){JwtUtils.userkey=key;}
    public void setExpire(Integer expire){
        JwtUtils.expire=expire;
    }

    public static String createAdminToken(Long id){
        return createToken(adminkey,id);
    }
    public static String createUserToken(Long id){
        return createToken(userkey,id);
    }


    public static String createToken(String key, Long id){
        try {
            Algorithm algorithm = Algorithm.HMAC256(key);
            Map<String, Object> map = new HashMap<String, Object>();
            Date nowDate = new Date();
            // 过期时间：2小时
            Date expireDate = expireDate();
            map.put("alg", "HS256");
            map.put("typ", "JWT");
            String token = JWT.create()
                    // 设置头部信息 Header
                    .withHeader(map)
                    // 设置 载荷 Payload
                    .withClaim("id", id)
                    .withIssuer(issuser)
                    .withSubject(subject)
                    .withAudience(client)
                    // 生成签名的时间
                    .withIssuedAt(nowDate)
                    // 签名过期的时间
                    .withExpiresAt(expireDate)
                    // 签名 Signature
                    .sign(algorithm);
            return token;
        } catch (JWTCreationException exception){
            exception.printStackTrace();
        }
        return null;
    }


    /**
     * 验证 Token 合法性
     * @param token
     */
    public static boolean checkAdminToken(String token) {
        try {
            JWT.require(Algorithm.HMAC256(adminkey)).build().verify(token);
        } catch (Exception e) {
//            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static Integer verifyAdminTokenAndGetId(String token){
        return verifyTokenAndGetId(adminkey,token);
    }

    public static Integer verifyUserTokenAndGetId(String token){
        return verifyTokenAndGetId(userkey,token);
    }

    public static Integer verifyTokenAndGetId(String key,String token) {
        Algorithm algorithm = Algorithm.HMAC256(key);
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer(issuser)
                .build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> claims = jwt.getClaims();
        Claim claim = claims.get("id");
        return claim.asInt();
    }

    private static Date expireDate(){
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.HOUR, expire);
        return nowTime.getTime();
    }

    public static void main(String[] args) {
//        String adminToken = createAdminToken(1L);
//        System.out.println(adminToken);
        boolean b = checkAdminToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ5b3VybGlmZSB0b2tlbiIsImF1ZCI6InlvdXJsaWZlYXBwIiwiaXNzIjoieW91cmxpZmUiLCJpZCI6MTksImV4cCI6MTcxODM0OTI2NSwiaWF0IjoxNzE4MjYyODY1fQ.qbNHWdFWkbjSzrd7Bjepy8TadJ-blLh0ncy3r1JrIUI");
        System.out.println(b);
    }
}
